import axios from 'axios'

// 提供todos相关的action

// 获取任务列表 异步
export const getList = () => {
  return async (dispatch) => {
    //   发请求
    const res = await axios.get('http://localhost:8888/todos')
    dispatch({
      type: 'GET_LIST',
      payload: res.data,
    })
  }
}
// 添加任务
export const addTodo = (name) => {
  return async (dispatch) => {
    //   发请求
    const res = await axios.post('http://localhost:8888/todos', {
      name,
      done: false,
    })
    dispatch({
      type: 'ADD_TODO',
      payload: res.data,
    })
  }
}
// 删除任务
export const delTodo = (id) => {
  return async (dispatch) => {
    // 处理异步
    await axios.delete(`http://localhost:8888/todos/${id}`)
    dispatch({
      type: 'DEL_TODO',
      payload: id,
    })
  }
}
export const changeDone = (id, done) => {
  return async (dispatch) => {
    // 发请求
    await axios.patch(`http://localhost:8888/todos/${id}`, {
      done,
    })
    dispatch({
      type: 'CHANGE_DONE',
      payload: {
        id,
        done,
      },
    })
  }
}
export const changeName = (id, name) => {
  return async (dispatch) => {
    // 发请求
    await axios.patch(`http://localhost:8888/todos/${id}`, {
      name,
    })
    dispatch({
      type: 'CHANGE_NAME',
      payload: {
        id,
        name,
      },
    })
  }
}
